﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Threading;

namespace JCPogi.Core {

    // taken from http://stackoverflow.com/questions/826096/c-sharp-cancelling-dowork-of-background-worker
    public class AbortableBackgroundWorker : BackgroundWorker {
        private Thread workerThread;

        public bool IsRunning {
            get {
                return workerThread != null;
            }
        }

        protected override void OnDoWork(DoWorkEventArgs e) {
            workerThread = Thread.CurrentThread;            
            try {
                base.OnDoWork(e);
            }
            catch (ThreadAbortException) {
                e.Cancel = true; //We must set Cancel property to true!
                Thread.ResetAbort(); //Prevents ThreadAbortException propagation
            }
        }

        public void Abort() {            
            if (workerThread != null) {
                workerThread.Abort();
                workerThread = null;
            }
        }
    }
}
